package com.aaa.aspect;

import com.aaa.annotation.MyLog;
import com.aaa.dao.SysOperLogMapper;
import com.aaa.entity.Staff;
import com.aaa.entity.SysOperLog;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

/**
 * @program: keyboard
 * @description:
 * @author: 闫克起
 * @create: 2024-03-28 16:30
 **/
@Component
@Aspect
public class LogAspect {
    @Pointcut("@annotation(com.aaa.annotation.MyLog)")
    private void pointcut(){}
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;
    @Autowired
    private SysOperLogMapper sysOperLogMapper;
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint){
            SysOperLog sysOperLog=new SysOperLog();
        try {
            //获取调用的方法对象
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            //获取方法上的注解对象
            MyLog annotation = method.getAnnotation(MyLog.class);
            String businessType = annotation.businessType();
            //获取操作类型
            sysOperLog.setBusinesstype(businessType);
            //获取方法名
            String name = method.getName();
            sysOperLog.setMethod(name);
            //获取请求方式
            sysOperLog.setRequestmethod(request.getMethod());
            //获取操作人
            Staff staff= (Staff) session.getAttribute("staff");
            sysOperLog.setOpername(staff.getStaffname());
            //请求的路径
            sysOperLog.setOperurl(request.getRequestURI());
            //获取请求人的ip
            sysOperLog.setOperip(request.getRemoteAddr());
            //获取请求的参数值
            Object[] args = joinPoint.getArgs();
            String params = Arrays.toString(args);
            sysOperLog.setOperparam(params);
            //获取方法返回的结果
            Object result = joinPoint.proceed();
            sysOperLog.setJsonresult(JSON.toJSONString(result));
            //状态
            sysOperLog.setStatus(0);
            return result;
        }catch (Throwable e){
            sysOperLog.setStatus(1);
        }finally {
            //添加日志
            //日期
            sysOperLog.setOpertime(new Date());
            sysOperLogMapper.insert(sysOperLog);
        }
        return new Result(500,"服务器错误", null);
    }
}
